

//overflow hidden     true :  hidden  ;     false :  overlay
function  slideCate($sel,off){
	if(off){
		$sel.slideDown();
		$('body').css('overflow','hidden');
	}else{
		$sel.slideUp();
		$('body').css('overflow','overlay');
	}
}



siteWindow('.win-delalert');
//获取所需元素
var $addCategory = $('.main .addcate'),
    $win_category = $('.win-category'),
    $cate_first = $('.win-category .list-first .check-list'),
    $cate_second = $('.win-category .list-second'),
    $cate_third = $('.win-category .list-third');
	
	
//定义变量
var selectedCategory = {},
	categoryTree = searchTree = null,
	service_cate = 10,        //最多10个专长品类
    inqure_cate = 3;          //最多3个营业品类;
	
	
//获取品类数据tree
$.ajax({
	type:"get",
	url:"http://v4.www.laisj.com/publics/base/companyProductTagTree",
	async:false,
	success:function(res){
		console.log(res);
        searchTree = res;
        return searchTree;
	},
	error:function(res){
		console.log(res);      //错误的对象
	}
});	
	


//“添加品类”按钮点击事件
$addCategory.on('click',function(){
	$cate_first.html('');
	$cate_second.html('');
	$cate_third.html('');
	
	//加载一级品类
	changeList('.win-category .list-first .check-list',searchTree.tree,1);
	//弹出品类弹窗
	slideCate($win_category,true);
});
//品类弹窗“取消”按钮
$win_category.on('click','.canclebtn',function(){
	var sel = '.win-category'
	$(sel+' input[type="reset"]').trigger('click');
	$(sel+ ' input').css('border-color','');
	slideCate($(sel),false);
	$cate_first.html('');
	$cate_second.html('');
	$cate_third.html('');
});
//品类弹窗“完成”按钮点击事件
$win_category.on('click','.centbtn',function(){
	
});




// 1.渲染品类列表方法
function changeList(selector, data, index){
	var datahtml = '',
        id = null,
        $checked = null;

    //一二三级品类所有选项
    var $firstSelect = null,
        $secondSelect = null,
        $thirdSelect = null;

    var firstparent = null;
    
    //生成dom元素      index      1:一级品类
    if(index == 1){
    	datahtml = listItem('first-cate', data, index);
        $(selector).html(datahtml);
        
        $firstSelect = $(selector + ' input[name="first-cate"]');
        $firstSelect.change(function(){
        	var thisindex = $(this).index(selector + ' input[name="first-cate"]');
        	$checked = $(selector+' input[name="first-cate"]:checked');
        	id = parseInt($checked.data('val'));
        	
        	//记录选中的一级品类
            firstparent = $checked.val();
            //判断是否已选择二级品类
            if (!$.isEmptyObject(selectedCategory[Object.keys(selectedCategory)[0]])) {
                delaertCate(selector, thisindex);
                return false;
            } else {
                $('.radio-wrap').removeClass('checked');
                $(this).parent().parent().addClass('checked');
            }
        	
        	selectedCategory = {};
        	selectedCategory[$checked.val()] = {};
        	
        	//改变一级品类时，清除二级、三级品类
        	clearChild(index);
        	
        	//需求方可以提交品类
            if (catePage == 'inquire') {
                changeBtn(true);
            } else {
                calOther();
            }
        	return changeList('.win-category .list-second',data[id],2);
        });
    }
    if(index == 2){
    	datahtml = '<p class="item-title">'+data.name+'</p>'+
					'<ul class="check-list clearfix">'+listItem('second-cate',data,index)+'</ul>';
		$(selector).html(datahtml);
		
		$secondSelect = $(selector+' input[name="second-cate"]');
		$secondSelect.change(function(){
			//判断是添加选中，还是取消选中
			var parent = $(this).data('parent');
            if ($(this).is(':checked')) {
            	//添加选中
                $(this).parent().addClass('checked');
                selectedCategory[parent][$(this).val()] = [];
            } else {
            	//取消选中
                $(this).parent().removeClass('checked');
                delete selectedCategory[parent][$(this).val()];
                if ($.isEmptyObject(selectedCategory[parent])) {
                    changeBtn(false);
                }
            }
            
            //改变二级品类时，清除三级品类
            clearChild(index);
            //更新三级品类
            $checked = $(selector + ' input[name="second-cate"]:checked');
            for (var i = 0; i < $checked.length; i++) {
                id = parseInt($checked[i].dataset.val);
                //记录选中的二级品类
                changeList('.win-category .list-third', data.children[id], 3);
            }
            
            //需求方可以提交品类
            if (catePage == 'inquire') {
                changeBtn(true);
            } else {
                calOther();
            }
		});
		categoryTree = data.children;
    }
    if(index == 3){
    	//判断是否有三级品类
    	if(data.children.length <= 0){
    		//没有三级品类
    		clearChild(index);
    		return false;
    	}
    	
    	datahtml = '<div class="item-li">'+
					'<p class="item-title">'+data.name+'</p>'+
					'<ul class="check-list">';
		datahtml+= listItem('third-cate',data,index) + '</ul>\n</div>';			
    	$(selector).append(datahtml);
    	
    	
    	firstparent = $('.list-first input:checked').val();
        $thirdSelect = $(selector + ' input[name="third-cate"]');
        //change事件
        $thirdSelect.unbind('change');
        $thirdSelect.bind('change', function () {
        	var _this = $(this);
            if (_this.is(':checked')) {
                _this.parent().addClass('checked');
                selectedCategory[firstparent][_this.data('parent')].push(_this.val());
            } else {
                _this.parent().removeClass('checked');
                selectedCategory[firstparent][_this.data('parent')].splice($.inArray(_this.val(), selectedCategory[firstparent][_this.data('parent')]), 1);
            }

            //判断是否选择末级品类
         	endCategory();
         	
        });
        if (selectedCategory[firstparent][data.id].length > 0) {
            selectcate(selectedCategory[firstparent][data.id], $thirdSelect);
        }
     	//需求方可以提交品类
        if (catePage == 'inquire') {
            changeBtn(true);
        }
    }
    return selectedCategory;
}

// 1.1三级不同的品类
function listItem(selname, data, index){
	console.log(data);
	var datahtml = dataChild = '';
	//index   1:  一级品类   ,   2:  二级品类    ,  3:  三级品类
	if(index == 1){
		for(i in data){
			datahtml+= '<li class="radio-wrapper" data-type="' + selname + '">'+
							'<input type="radio" name="' + selname + '" id="' + selname + i + '" value="' + data[i].id + '" data-val="' + i + '" />'+
							'<label for="' + selname + i + '" class="check-text">'+
							 	'<span class="check"></span>'+data[i].name+
						 	'</label>'+
					 	'</li>';
			
		}
		return datahtml;
	}
	if(index == 2){
		dataChild = data.children;
		for(i in dataChild){
			datahtml+= '<li class="checkbox-wrapper" data-type="' + selname + '">'+
								'<input type="checkbox" name="' + selname + '" id="' + selname + i + '" value="' + dataChild[i].id + '" data-parent="' + data.id + '" data-val="' + i + '"/>'+
								'<label for="' + selname + i + '" class="checkbox-label">'+
									'<span class="checkbox-check"></span>'+
									'<span class="checkbox-check-text">'+dataChild[i].name+'</span>'+
								'</label>'+
							'</li>';
		}
		return datahtml;
	}
	if(index == 3){
		dataChild = data.children;
		for(i in dataChild){
			datahtml+= '<li class="checkbox-wrapper" data-type="' + selname + '">'+
								'<input type="checkbox" name="' + selname + '" id="' + selname + dataChild[i].id + i + '" value="' + dataChild[i].id + '" data-parent="' + data.id + '" data-val="' + i + '"/>'+
								'<label for="' + selname + dataChild[i].id + i + '" class="checkbox-label">'+
									'<span class="checkbox-check"></span>'+
									'<span class="checkbox-check-text">'+dataChild[i].name+'</span>'+
								'</label>'+
							'</li>';
		}
		return datahtml;
	}
}

// 1.2change品类视图
function clearChild(index){
	if (index == 1) {
        $cate_second.html('');
        $cate_third.html('');
        changeBtn(false);
        return false;
    }
    if (index == 2) {
        $cate_third.html('');
        return false;
    }
    if (index == 3) {
        //末级品类
        console.log('no more');
        return false;
    }
}

// 1.3改变添加按钮   true:可点击    false:不可点击
function changeBtn(off) {
	var $saveDatabtn = $('.win-category .centbtn');
    if (off) {
        $saveDatabtn.removeClass('disabled');
        $saveDatabtn.removeAttr('disabled');
    } else {
    	$saveDatabtn.addClass('disabled');
        $saveDatabtn.attr('disabled', 'true');
    }
}


// 1.4判断是否选择末级品类(服务方)
function endCategory(){
	var firstparent = $('.list-first input:checked').val();
    //判断是否是服务方
    if (catePage != 'service') {
        return false;
    }
    
    //服务方
    var selected = selectedCategory[firstparent];
    var thirdLength = null,
        nowEndNum = 0;
//  calOther();

    //判断是否选择末级品类
    for (var i in selected) {
        for (var j in categoryTree) {
            if (categoryTree[j].id == i) {
                thirdLength = categoryTree[j].children.length;
                if (selected[i].length < 1 && thirdLength > 0) {
                    changeBtn(false);
                    return false;
                }
            }
        }
    }
    changeBtn(true);
}

// 1.5 服务方品类个数判断
var lastLeveSize = 0;
function calOther() {
    var firstparent = $('.list-first input:checked').val();
    //判断还可以选择多少个品类
    //1.2服务方：最多10个末级品类
    var off = true,
        selected = null,
        nowEndNum = 0;
    var firstsel = $('.list-first li'),
        secondsel = $('.list-second li'),
        thirdsel = $('.list-third .checkbox-wrapper');

    var lastSize = searchTree.lastLevelSize,
        resultSize = 0;
    if ($('.win-category .centbtn').data('type') == 'edit') {
        lastSize = lastSize - editlastSize;
    }

    //判断是否选择了二级品类
    if ($.isEmptyObject(selectedCategory[firstparent])) {
        off = false;
        otherdisabled(off, secondsel, thirdsel);
        return false;
    }

    //选择了二级品类
    selected = selectedCategory[firstparent];
    for (var i in selected) {
        for (var j in categoryTree) {
            if (categoryTree[j].id == i) {
                thirdLength = categoryTree[j].children.length;
                if (selected[i].length < 1 && thirdLength < 1) {
                    nowEndNum = nowEndNum + 1;
                } else {
                    nowEndNum = nowEndNum + selected[i].length;
                }
            }
        }
    }

    //计算显示服务方还可以选择多少个专长品类
    resultSize = service_cate - lastSize - nowEndNum;
//  console.log(service_cate, lastSize, nowEndNum, editlastSize);

    if (resultSize <= 0) {
        otherdisabled(off, secondsel, thirdsel);
    }
    if (resultSize > 0) {
        off = false;
        otherdisabled(off, secondsel, thirdsel);
    }
}

// 1.6设置选项不可用(即该一级品类已被选择了)
function disabled(sel, noseleted) {
    var _this = null,
        $input = sel.find('input');
    for (var i in noseleted) {
        for (var j = 0; j < $input.length; j++) {
            if (noseleted[i].id == $input.eq(j).val() && noseleted[i].selected == 'true') {
                _this = sel.eq(j);
                _this.addClass('disabled');
                _this.find('input').attr('disabled', 'false');
                _this.find('input').attr('checked', 'true');
                _this.find('label').attr('disabled', 'false');
            }
        }
    }
}

//1.7设置其他不可用(未选中:品类个数有限制)
//1.需求方：最多3个一级品类，二三级不限个数
//2.服务方：最多10个末级品类
function otherdisabled(off, secondsel, thirdsel) {
    var $secondinput = secondsel.find('input'),
        $thirdinput = thirdsel.find('input');

    //禁用
    addDisable(secondsel, off);
    addDisable(thirdsel, off);
    if (!off) {
        return false;
    }
    for (var i in selectedCategory) {
        for (var m in selectedCategory[i]) {
            //二级品类
            for (var j = 0; j < $secondinput.length; j++) {
                if ($secondinput.eq(j).val() == m) {
                    _this = secondsel.eq(j);
                    addDisable(_this, false);
                }
            }
            for (var n = 0; n < selectedCategory[i][m].length; n++) {
                //三级品类
                for (var k = 0; k < $thirdinput.length; k++) {
                    if ($thirdinput.eq(k).val() == selectedCategory[i][m][n]) {
                        _this = thirdsel.eq(k);
                        addDisable(_this, false);
                    }
                }
            }
        }
    }
}
function addDisable(_this, off) {
    //默认 true:禁用      false:启用
    _this.addClass('disabled');
    _this.find('input').attr('disabled', 'false');
    _this.find('label').attr('disabled', 'false');
    if (!off) {
        _this.removeClass('disabled');
        _this.find('input').removeAttr('disabled');
        _this.find('label').removeAttr('disabled');
    }
}

// 1.8标记已选中的品类    三级品类
function selectcate(selectedData, category) {
    for (var i = 0; i < selectedData.length; i++) {
        for (var j = 0; j < category.length; j++) {
            if (selectedData[i] == category.eq(j).val()) {
                //标记已选中
            category.eq(j).attr('checked', 'true');

            _this = category.eq(j);
            if (_this.is(':checked')) {
                _this.parent().addClass('checked');
                }
                endCategory();
            }
        }
    }
}




// 搜索视图 变换公共方法
var $backbtn = $('.win-category .backbtn'),
	$keyword_input = $('.win-category .header-keyword'),
	$clear_keyword = $('.win-category .closebtn'),
	$category_search = $('.win-category .category-search');
$keyword_input.on('focusin',function(){
	changeSearch(true);
});
$win_category.on('click','.backbtn',function(){
	changeSearch(false);
});
$win_category.on('click','.closebtn',function(){
	$(this).css('display','none');
	$keyword_input.val('');
});
// off : true 搜索状态显示      off : false	 搜索状态隐藏
function changeSearch(off){ 
	if(off){
		$backbtn.css('display','inline-block');
		$keyword_input.css('width','calc(100% - 4.75rem)');
		$category_search.fadeIn();
	}else{
		$backbtn.css('display','none');
		$keyword_input.css('width','calc(100% - 3rem)');
		$keyword_input.val('');
		$category_search.fadeOut();
		$('.win-category .search-list').html('');
		$clear_keyword.css('display','none');
	}
}
// 2.品类模糊搜索
function searchKeywrod() {
	$clear_keyword.css('display','block');
	
    var _this = $('.win-category .header-keyword');
    var cateTree = searchTree.tree,
        keyword = _this.val();

    //记录搜索结果个数
    var seli_num = 0;

    var $select_list = $('.win-category .search-list');
    $select_list.html('');

    for (var i in cateTree) {
        if (cateTree[i].name.indexOf(keyword) != -1) {
            for (var f in cateTree[i].children) {
                if (cateTree[i].children[f].children.length > 0) {
                    for (var t in cateTree[i].children[f].children) {
                        seli_num++;
                        $select_list.append('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[f].id + '" data-thirdid="' + cateTree[i].children[f].children[t].id + '">' + cateTree[i].name + '-' + cateTree[i].children[f].name + '-' + cateTree[i].children[f].children[t].name + '</li>');
                    }
                }
                if (cateTree[i].children[f].children.length <= 0) {
                    seli_num++;
                    $select_list.append('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[f].id + '">' + cateTree[i].name + '-' + cateTree[i].children[f].name + '</li>');
                }
            }

            searchResult();
            continue;
        }
        for (var j in cateTree[i].children) {
            if (cateTree[i].children[j].name.indexOf(keyword) != -1) {
                //console.log(cateTree[i].children[j].name);

                if (cateTree[i].children[j].children.length > 0) {
                    for (var f in cateTree[i].children[j].children) {
                        seli_num++;
                        if ($select_list.find('.list-item').length > 0) {
                            $('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '" data-thirdid="' + cateTree[i].children[j].children[f].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '-' + cateTree[i].children[j].children[f].name + '</li>').insertBefore($select_list.find('.li').first());
                        } else {
                            $select_list.append('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '" data-thirdid="' + cateTree[i].children[j].children[f].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '-' + cateTree[i].children[j].children[f].name + '</li>');
                        }
                    }
                }
                if (cateTree[i].children[j].children.length <= 0) {
                    seli_num++;
                    if ($select_list.find('.list-item').length > 0) {
                        $('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '</li>').insertBefore($select_list.find('.li').first());
                    } else {
                        $select_list.append('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '</li>');
                    }
                }

                searchResult();
                continue;
            }
            for (var m in cateTree[i].children[j].children) {
                if (cateTree[i].children[j].children[m].name.indexOf(keyword) != -1) {
                	//console.log(cateTree[i].children[j].children[m].name);

                    seli_num++;
                    if ($select_list.find('.list-item').length > 0) {
                        $('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '" data-thirdid="' + cateTree[i].children[j].children[m].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '-' + cateTree[i].children[j].children[m].name + '</li>').insertBefore($select_list.find('.li').first());
                    } else {
                        $select_list.append('<li class="list-item" data-firstid="' + cateTree[i].id + '" data-secondid="' + cateTree[i].children[j].id + '" data-thirdid="' + cateTree[i].children[j].children[m].id + '">' + cateTree[i].name + '-' + cateTree[i].children[j].name + '-' + cateTree[i].children[j].children[m].name + '</li>');
                    }
                    searchResult();
                }
            }
        }
    }

    //判断是否有内容
    var $ondata = $('.win-category .list-nodata');
    if (seli_num <= 0) {
        //没有搜索结果
        $ondata.css('display','block');
    } else {
        $ondata.css('display','none');
    }
    return false;
}

function searchResult() {
    var $select_wrap = $('.win-category .header-keyword'),
        $select_list = $('.win-category .search-list'),
        $select_li = $('.win-category .search-list .list-item'),
        firstid = null,
        secondid = null,
        thirdid = null;

    var this_id = null;
    $select_li.unbind('click');
    $select_li.click(function () {
        this_id = $(this).index('.win-category .search-list .li');

        firstid = $(this).data('firstid'),
            secondid = $(this).data('secondid'),
            thirdid = $(this).data('thirdid');

        //
        for (var i = 0; i < $('.list-first input').length; i++) {
            if ($('.list-first input').eq(i).val() == firstid) {

                //判断这个一级品类是否已经选择过
                if ($('.list-first input').eq(i).attr('disabled') != undefined) {
                    alertbox('已添加该大类，请在对应大类中编辑');
//                  $select_list.slideUp();
                    changeSearch(false);
                    return false;
                }

                if (!$.isEmptyObject(selectedCategory) && $('.list-first input').eq(i).is(':checked') == false) {
                    if (!$.isEmptyObject(selectedCategory[Object.keys(selectedCategory)[0]])) {
                        delaertCate('.list-first', i);

                        var $btn_conf = $('.win-delalert .btn-conf');

                        $btn_conf.attr('data-thisindex', this_id);
                        return false;
                    }
                }

//              $select_list.slideUp();
                changeSearch(false);
                $('.list-first input').eq(i).trigger('click');


                for (var j = 0; j < $('.list-second input').length; j++) {
                    if ($('.list-second input').eq(j).val() == secondid) {
                        if (!$('.list-second input').eq(j).is(':checked')) {
                            $('.list-second input').eq(j).parent().find('.checkbox-label').trigger('click');
                        }

                        for (var n = 0; n < $('.list-third input').length; n++) {
                            if ($('.list-third input').eq(n).val() == thirdid && !$('.list-third input').eq(n).is(':checked')) {
                                $('.list-third input').eq(n).parent().find('.checkbox-label').trigger('click');
                            }
                        }
                    }
                }
            }
        }
    });
}


// 1.8判断已选择其它二三级品类  从而给出相应的提示
function delaertCate(selector, index) {

    var $input = $(selector + ' input');

    $input.eq(index).prop('checked', 'false');
    for (var i = 0; i < $input.length; i++) {
        if ($input.eq(i).val() == Object.keys(selectedCategory)[0]) {
            $input.eq(i).prop('checked', 'true');
        }
    }

    var $btn_conf = $('.win-delalert .btn-conf'),
        $delart_view = $('.win-delalert');

    $('.win-delalert .title').text('确定更改品类,所选品类将清空！');
    winFade($delart_view,true);
    $btn_conf.attr('data-change', 'change');
    $btn_conf.attr('data-thisid', index);
}


//选中了二级、三级品类下，更改一级品类  的提示方法
cateDelate();
function cateDelate() {
    var $btn_conf = $('.win-delalert .btn-conf'),
        $btn_re = $('.win-delalert .btn-re'),
        $delart_view = $('.win-delalert');

    $btn_conf.click(function () {

        //搜索下拉点击 切换一级品类
        if ($(this).attr('data-change') == 'change' && $(this).attr('data-thisindex') != undefined) {
            selectedCategory = {};
            $('.win-category .search-list .list-item').eq($(this).attr('data-thisindex')).trigger('click');

            $btn_re.trigger('click');
        }
        //直接点击一级品类
        if ($(this).attr('data-change') == 'change' && $(this).attr('data-thisindex') == undefined) {
            selectedCategory = {};
            $('.win-category .list-first input').eq($(this).attr('data-thisid')).trigger('click');

            $btn_conf.removeAttr('data-change');
            $btn_conf.removeAttr('data-thisid');
            winFade($delart_view,false);
        }
    });
    $btn_re.click(function () {
        $btn_conf = $('.win-delalert .btn-conf');

        //搜索下拉点击 切换一级品类
        if ($btn_conf.attr('data-change') == 'change' && $btn_conf.attr('data-thisindex') != undefined) {
            $btn_conf.removeAttr('data-change');
            $btn_conf.removeAttr('data-thisindex');
            winFade($delart_view,false);
        }
        //直接点击一级品类
        if ($btn_conf.attr('data-change') == 'change' && $btn_conf.attr('data-thisindex') == undefined) {
            $btn_conf.removeAttr('data-change');
            $btn_conf.removeAttr('data-thisid');
            winFade($delart_view,false);
        }
    });
}






